Logout

Home Topic 4 Last Next

For Loops Applied With Arrays

Array declared the brackets way,
and assigned within the for loop:

21        double [] myDoubleArray = new double[5];
22
23        for(int i = 0; i < myDoubleArray.length; i++){
24            myDoubleArray[i] = Math.random();
25            System.out.println(myDoubleArray[i]);
26        }



Scanner used for assigning values
from the user, within the for loop:

6
7        Scanner snr = new Scanner(System.in);
8
9        int [] arr = new int[5];
10        for(int i = 0; i < arr.length; i++){
11           System.out.println("What's the next number to add to the array?");
12            arr[i] = snr.nextInt();
13        }



Array declared the braces way, and then
the elements printed out within the for loop:

22
23        int [] anotherArr = {234, 987, 64, 9234, 454};
24        for(int i = 0; i < anotherArr.length; i++){
25            System.out.println(anotherArr[i]);
26        }



Looping through an array to both assign values,
and determine which element is the smallest value:

68
69  public static void findMinTemperature(){
70      double [] bkkTemps = new double[100];
71
72      double min = 999999;
73      for(int i = 0; i < bkkTemps.length; i++){
74          bkkTemps[i] = Math.random()*24 + 16;
75          if(bkkTemps[i] < min){
76             min = bkkTemps[i];
77          }
78      }
79      System.out.println("The lowest temperature was " + (int) min + ".");
80  }



Using a loop to help determine the average of the array:

42
43   public static void findAverageTemperature(){
44       double [] pragueTemps = new double[365];
45
46      double total = 0;
47      for(int i = 0; i < pragueTemps.length; i++){
48          pragueTemps[i] = Math.random()*70 -30;
49          total = total + pragueTemps[i];
50      }
51      double averageTemp = total/ pragueTemps.length;
52      System.out.println("The average temperature is: " + averageTemp);
53  }


Try, on your own, some of these:

Outputting all of the negative values of an array of numbers.

Outputting all of the even values of an array of numbers.

Outputting all of the negative odd values of an array of numbers.


And later, after learning about collections/lists:

Doing all of the above, but instead of outputting the values, adding them to an OurList, or LinkedList etc.